// pages/login/login.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    time: '12:30',
    username: '',
    password: '',
    rememberPassword: false,
    isLoading: false,
    errorMsg: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 更新当前时间
    this.updateTime();
    this.getTimerID = setInterval(this.updateTime, 60000);
    
    // 获取存储的用户名和密码
    const username = wx.getStorageSync('username') || '';
    const password = wx.getStorageSync('password') || '';
    const rememberPassword = !!password;
    
    this.setData({
      username,
      password,
      rememberPassword
    });
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(this.getTimerID);
  },

  updateTime: function() {
    const date = new Date();
    const hours = date.getHours();
    const minutes = date.getMinutes();
    this.setData({
      time: `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`
    });
  },

  // 输入用户名
  inputUsername: function(e) {
    this.setData({
      username: e.detail.value
    });
  },

  // 输入密码
  inputPassword: function(e) {
    this.setData({
      password: e.detail.value
    });
  },

  // 切换记住密码
  toggleRememberPassword: function() {
    this.setData({
      rememberPassword: !this.data.rememberPassword
    });
  },

  // 登录
  login: function() {
    const { username, password, rememberPassword } = this.data;
    
    if (!username.trim()) {
      this.setData({
        errorMsg: '请输入用户名'
      });
      return;
    }
    
    if (!password.trim()) {
      this.setData({
        errorMsg: '请输入密码'
      });
      return;
    }
    
    this.setData({
      isLoading: true,
      errorMsg: ''
    });
    
    // 模拟登录请求
    setTimeout(() => {
      // 在实际项目中，这里应该调用真实的登录API
      const success = username === 'admin' && password === '123456';
      
      if (success) {
        // 保存用户名和密码
        wx.setStorageSync('username', username);
        if (rememberPassword) {
          wx.setStorageSync('password', password);
        } else {
          wx.removeStorageSync('password');
        }
        
        // 保存登录状态
        wx.setStorageSync('isLoggedIn', true);
        
        // 跳转到首页
        wx.reLaunch({
          url: '/pages/dashboard/dashboard'
        });
      } else {
        this.setData({
          errorMsg: '用户名或密码错误',
          isLoading: false
        });
      }
    }, 1000);
  },

  // 忘记密码
  forgotPassword: function() {
    wx.showToast({
      title: '请联系管理员重置密码',
      icon: 'none'
    });
  }
}) 